package com.jshongli.myapplication.common.utils;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ScaleXSpan;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Reuel
 */

public class StringUtils {

    /**
     * 判断是否为数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0; ) {
            if (!Character.isDigit(str.charAt(i)) && !".".equals(String.valueOf(str.charAt(i)))) {
                return false;
            }
        }
        return true;
    }

    //region  String  -->  Integer
    public static boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    public static int stringToInteger(String s) {
        if (isInteger(s)) {
            return Integer.valueOf(s);
        } else {
            return 0;
        }
    }
    //endregion

    //region String  -->  Double
    public static boolean isDouble(String num) {
        if (!TextUtils.isEmpty(num)) {
            try {
                double d = Double.valueOf(num);
                return true;
            } catch (Exception e) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static double stringToDouble(String s) {
        if (isDouble(s)) {
            return Double.valueOf(s);
        } else {
            return 0.0;
        }
    }
    //endregion

    //region String  -->  Double
    public static boolean isFloat(String num) {
        if (!TextUtils.isEmpty(num)) {
            try {
                float d = Float.valueOf(num);
                return true;
            } catch (Exception e) {
                return false;
            }
        } else {
            return false;
        }
    }

    public static float stringToFloat(String s) {
        if (isFloat(s)) {
            return Float.valueOf(s);
        } else {
            return 0;
        }
    }
    //endregion

    /**
     * Html转化为String(去除换行)
     *
     * @param s
     * @return
     */
    public static CharSequence stripHtml(String s) {
        if (s != null) {
            return Html.fromHtml(s).toString().replace('\n', (char) 32)
                    .replace((char) 160, (char) 32).replace((char) 65532, (char) 32).trim();
        } else {
            return "无内容";
        }
    }



    public String flirJsonToSTring(Context context, String fileName){
        StringBuilder stringBuilder = new StringBuilder();
        try {
            AssetManager assetManager = context.getAssets();
            BufferedReader bf = new BufferedReader(new InputStreamReader(assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine())!=null){
                stringBuilder.append(line);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    /**
     * 判断edittext是否null
     */
    public static String checkEditText(EditText editText) {
        if (editText != null && editText.getText() != null
                && !(editText.getText().toString().trim().equals(""))) {
            return editText.getText().toString().trim();
        } else {
            return "";
        }
    }

    public static boolean editTextIsNull(EditText editText) {
        if (editText != null && editText.getText() != null
                && !(editText.getText().toString().trim().equals(""))) {
            return false;
        } else {
            return true;
        }
    }

    public static Spanned stringToSpan(String src) {
        return src == null ? null : Html.fromHtml(src.replace("\n", "<br />"));
    }

    public static String colorFont(String src, String color) {
        StringBuffer strBuf = new StringBuffer();

        strBuf.append("<font color=").append(color).append(">").append(src)
                .append("</font>");
        return strBuf.toString();
    }

    public static String makeHtmlNewLine() {
        return "<br />";
    }

    public static String makeHtmlSpace(int number) {
        final String space = "&nbsp;";
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < number; i++) {
            result.append(space);
        }
        return result.toString();
    }


    /**
     * 将给定的字符串给定的长度两端对齐
     *
     * @param str  待对齐字符串
     * @param size 汉字个数，eg:size=5，则将str在5个汉字的长度里两端对齐
     * @Return
     */
    public static SpannableStringBuilder justifyString(String str, int size) {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        if (TextUtils.isEmpty(str)) {
            return spannableStringBuilder;
        }
        char[] chars = str.toCharArray();
        if (chars.length >= size || chars.length == 1) {
            return spannableStringBuilder.append(str);
        }
        int l = chars.length;
        float scale = (float) (size - l) / (l - 1);
        for (int i = 0; i < l; i++) {
            spannableStringBuilder.append(chars[i]);
            if (i != l - 1) {
                SpannableString s = new SpannableString("　");//全角空格
                s.setSpan(new ScaleXSpan(scale), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableStringBuilder.append(s);
            }
        }
        return spannableStringBuilder;
    }

    public static String divide100(String value,int type) {
//        DecimalFormat format = new DecimalFormat("#0.00");
        if(!TextUtils.isEmpty(value)){
            BigDecimal v1 = new BigDecimal(value);
            v1 = v1.divide(new BigDecimal(100),2, BigDecimal.ROUND_HALF_UP);
            if(type == 0){
                return v1.toString()+"m";
            }else if(type == 1){
                return v1.toString()+"m³/s";
            }else if(type == 2){
                return v1.toString();
            }

        }
        return "";

    }

    public static String divide10(String value,int type) {
//        DecimalFormat format = new DecimalFormat("#0.00");
        if(!TextUtils.isEmpty(value)){
            BigDecimal v1 = new BigDecimal(value);
            v1 = v1.divide(new BigDecimal(10),1, BigDecimal.ROUND_HALF_UP);
            if(type==0){
                return v1.toString();
            }else {
                return v1.toString()+"℃";
            }

        }

        return "";

    }

    public static <T> List<T> castList(Object obj, Class<T> clazz){
        List<T> result = new ArrayList<>();
        if(obj instanceof List<?>){
            for (Object o : (List<?>) obj){
                result.add(clazz.cast(o));
            }
            return result;
        }
        return new ArrayList<>();
    }

    //region 空显示
    public static String RemoveNull(String item) {
        return (item != null ? item : "");
    }

    public static String replaceNull(String item) {
        return (!TextUtils.isEmpty(item) ? item : "-");
    }
    //endregion


    //region 保留两位
    public static String twoDecimal(String num){
        DecimalFormat decimalFormat =new DecimalFormat("0.00");
        if(isFloat(num)){
            return decimalFormat.format(stringToFloat(num));
        }else {
            return "0";
        }
    }
    //endregion

}
